package org.corey.share.db.service;

import java.util.StringTokenizer;

import org.corey.share.db.dao.CoreyFileDao;
import org.corey.share.db.entity.CoreyFile;
import org.corey.share.db.manager.DefaultDaoFactory;
import org.corey.share.db.manager.EM;
import org.corey.share.misc.Common;
import org.corey.share.misc.Constants;

public class CoreyFileServiceImpl implements CoreyFileService {
	public CoreyFileDao dao = new DefaultDaoFactory().createCoreyFileDao();

	public CoreyFile getFile(String url) {
			StringTokenizer tokenizer = new StringTokenizer(Constants.URL_CUSTROM_SEPERATOR+url,
					Constants.URL_CUSTROM_SEPERATOR);
			Long user = null;
			String respository = "";
			String serverSideFileName = "";
			if (tokenizer.hasMoreTokens()) {
				user = Common.parseLong(tokenizer.nextElement());
			} else {
				return null;
			}
			if (tokenizer.hasMoreTokens()) {
				respository = tokenizer.nextToken();
			} else {
				return null;
			}
			if (tokenizer.hasMoreTokens()) {
				serverSideFileName = tokenizer.nextToken();
			} else {
				return null;
			}
			return dao.getCoreyFileByUrl(user, respository, serverSideFileName);
	}

	public boolean deleteFile(String url) {
		StringTokenizer tokenizer = new StringTokenizer("url",
				Constants.URL_CUSTROM_SEPERATOR);
		EM.beginTransaction();
		Long user = null;
		String respository = "";
		String serverSideFileName = "";
		if (tokenizer.hasMoreTokens()) {
			user = Common.parseLong(tokenizer.nextElement());
		} else {
			return false;
		}
		if (tokenizer.hasMoreTokens()) {
			respository = tokenizer.nextToken();
		} else {
			return false;
		}
		if (tokenizer.hasMoreTokens()) {
			serverSideFileName = tokenizer.nextToken();
		} else {
			return false;
		}
		boolean result = dao.deleteFile(user, respository, serverSideFileName);
		EM.commitTransaction();
		return result;
	}

	public String uploadFile(CoreyFile file) {
		if (file == null) {
			throw new IllegalArgumentException();
		}
		EM.beginTransaction();
		dao.saveFile(file);
		String url =file.getId()+"";
		EM.commitTransaction();
		return url;
	}
	
	public static void main(String[] args) {
		CoreyFileServiceImpl i=new CoreyFileServiceImpl();
		i.getFile("148275|aaa|20100126022805");
	}

	public CoreyFile getFile(Long id) {
		return dao.getFileById(id);
	}
	
	

}
